package com.kmxd.ams.core.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kmxd.ams.core.common.bo.LoginUser;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.exception.BizException;
import com.kmxd.ams.core.result.ResultCode;
import com.kmxd.ams.core.util.SecurityUtil;
import java.util.Date;
import java.util.Objects;
import org.apache.ibatis.reflection.MetaObject;

/**
 * MP注入处理器
 *
 * @author admin
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

  public static final String CREATE_TIME = "createTime";
  public static final String CREATE_BY = "createBy";

  public static final String UPDATE_TIME = "updateTime";
  public static final String UPDATE_BY = "updateBy";

  @Override
  public void insertFill(MetaObject metaObject) {
    try {
      if (metaObject.hasGetter(CREATE_TIME) && metaObject.getValue(CREATE_TIME) == null) {
        this.strictInsertFill(metaObject, CREATE_TIME, Date.class, new Date());
      }
      LoginUser loginUser = SecurityUtil.getLoginUser();
      if (metaObject.hasGetter(CREATE_BY) && metaObject.getValue(CREATE_BY) == null) {
        this.strictInsertFill(
            metaObject,
            CREATE_BY,
            Long.class,
            Objects.isNull(loginUser) ? null : loginUser.getSysUser().getId());
      }
    } catch (Exception e) {
      throw BizException.instance(
          ErrorCode.EXCEPTION, ResultCode.INTERNAL_SERVER_ERROR.getMessage());
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    try {
      if (metaObject.hasGetter(UPDATE_TIME)) {
        this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
      }
      if (metaObject.hasGetter(UPDATE_BY)) {
        LoginUser loginUser = SecurityUtil.getLoginUser();
        this.setFieldValByName(
            "update_by",
            Objects.isNull(loginUser) ? null : loginUser.getSysUser().getId().toString(),
            metaObject);
      }
    } catch (Exception e) {
      throw BizException.instance(
          ErrorCode.EXCEPTION, ResultCode.INTERNAL_SERVER_ERROR.getMessage());
    }
  }
}
